package com.wealth.merchant.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.repository.MerchantCustomerDao;

/**
 * 商户
 * @author chan
 */

public class MerchantDaoImpl implements MerchantCustomerDao {

	@PersistenceContext
 	private EntityManager em;
	
	/** 加载更多商户 */
	@Override
	@SuppressWarnings(value="all")
	public List<Merchant> ajaxMerchant(Long marketid,Long categoryid,Long districtid,Integer isParentCategory,  Integer status,String busId, Integer index,Integer offset) {
		StringBuffer sql = new StringBuffer();
		sql.append("select DISTINCT a.* from t_merchant_merchant a left join t_merchant_market b on  b.id = a.market_id ");
		//过滤:分类
		if(categoryid!=-1){
			sql.append(" left join commodity_goods c on c.merchant_id = a.id ");
			sql.append(" left join commodity_category d on d.id = c.category_id ");
		}
		//过滤:商圈
		if(districtid!=-1){
			sql.append(" left join t_merchant_business_district e on e.id = a.district_id ");
		}
		sql.append(" where a.status ="+status);	//商户状态
		if(categoryid!=-1){
			sql.append(" and c.status = 2 ");				//商品状态
		}
		sql.append(" and  a.market_id = "+marketid );
		if(categoryid!=-1){
			if(isParentCategory==1){
				sql.append(" and d.parent_id = "+categoryid);
			}else{
				sql.append(" and d.id = "+categoryid);
			}
		}
		if(districtid!=-1){
			sql.append(" and e.id in ("+busId+") ");
		}
		sql.append(" and  a.id >"+index );
		sql.append(" order by a.id asc");
		sql.append(" limit "+offset);
		Query query = em.createNativeQuery(sql.toString(), Merchant.class);
		List<Merchant> list = (List<Merchant>) query.getResultList();
		return list;
	}
	
	
	/** 搜索加载市场 */
	@Override
	@SuppressWarnings(value="all")
	public List<Merchant> ajaxSearchMerchant(Long marketid,String name,  Integer status, Integer index,Integer offset){
		StringBuffer sql = new StringBuffer();
		sql.append("select DISTINCT a.* from t_merchant_merchant a left join t_merchant_market b on  b.id = a.market_id ");
		sql.append(" left join commodity_goods c on c.merchant_id = a.id ");
		sql.append(" where a.status ="+status);
		sql.append(" and  c.status = 2 " );
		sql.append(" and  a.market_id = "+marketid );
		sql.append(" and  c.name like '%"+name+"%' ");
		sql.append(" and  a.id >"+index );
		sql.append(" order by a.id asc");
		sql.append(" limit "+offset);
		Query query = em.createNativeQuery(sql.toString(), Merchant.class);
		List<Merchant> list = (List<Merchant>) query.getResultList();
		return list;
		
	}
}


